package org.androidpn.server.entity;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.androidpn.server.util.XMLUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * entity 好友
 * 
 * @author 蔡琪
 * 
 */
@Entity
@Table(name = "tk_friend")
public class Friend extends BaseEntity {

	private static final long serialVersionUID = 7455021909829279639L;

	/** 好友备注 */
	@Column(name = "remark", length = 10)
	private String remark;

	/** 是否通过,true,表示同意添加请求,false表示暂未通过添加请求,拒绝时删除该好友信息 */
	@Column(name = "isPassed")
	private Boolean isPassed;

	/** 好友所关联的角色 */
	@ManyToOne(fetch = FetchType.EAGER)
	private Role role;

	/** 好友分组 */
	@ManyToOne(fetch = FetchType.EAGER)
	private FriendGroup friendGroup;

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public Boolean getIsPassed() {
		return isPassed;
	}

	public void setIsPassed(Boolean isPassed) {
		this.isPassed = isPassed;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public FriendGroup getFriendGroup() {
		return friendGroup;
	}

	public void setFriendGroup(FriendGroup friendGroup) {
		this.friendGroup = friendGroup;
	}

	/**
	 * 从xml字符串中解析出Friend
	 * 
	 * @param xml
	 *            xml字符串
	 * @return Room对象
	 */
	@Transient
	public static Friend fromXML(String xml) {
		Friend friend = BaseEntity.fromXML(xml, Friend.class);
		Document doc;
		try {
			doc = DocumentHelper.parseText(xml);
			Element element = doc.getRootElement();
			// 组装Friend信息
			String remark = element.elementText("remark");
			/** 角色信息 */
			Role role = null;
			Element roleElement = element.element("role");
			if (roleElement != null) {
				role = Role.fromXML(roleElement.asXML());
			}
			friend.setRemark(remark);
			friend.setRole(role);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return friend;
	}

	/**
	 * 将当前对象转化为xml字符串
	 * 
	 * @return
	 */
	@Transient
	public String toXML() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("<friend>");
		buffer.append(super.toXML());
		buffer.append(XMLUtils.createSingleNode("remark", this.remark));
		if (this.role != null) {
			buffer.append(role.toXML());
		}
		buffer.append("</friend>");
		return buffer.toString();
	}
}
